package com.mvp.shq.washer.ui.feendBack;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.ImageAdapter;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.RecyclerViewDivider;
import com.mvp.shq.washer.utils.StringUtils;
import com.mvp.shq.washer.utils.T;
import com.mvp.shq.washer.utils.UriToPathUtil;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@RuntimePermissions
public class FeedBackActivity extends BaseActivity<Presenter, Model> implements FeedBackConstract.View {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_et_count)
    TextView tvEtCount;
    @BindView(R.id.tv_img_count)
    TextView tvImgCount;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    private List<String> imgs;
    private List<File> files;
    private int compressIndex = 0;
    private ImageAdapter adapter;
    private int imgPosition = -1;
    private final int MAX_IMG = 2;
    @Override
    public int getLayoutId() {
        return R.layout.activity_feed_back;
    }

    @Override
    public void initView() {
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvEtCount.setText(etContent.getText().toString().length()+"/200");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        imgs = new ArrayList<>();
        imgs.add(ImageAdapter.DEFAULT_IMG);
        tvImgCount.setText("0/"+MAX_IMG);
        adapter = new ImageAdapter(context,imgs, EventCode.FEEDBACK_IMG);
        recyclerview.setLayoutManager(new GridLayoutManager(context,3, LinearLayoutManager.VERTICAL,false));
        RecyclerViewDivider divider1 = new RecyclerViewDivider(context,LinearLayoutManager.VERTICAL,28, ContextCompat.getColor(context,R.color.white));
        recyclerview.addItemDecoration(divider1);
        recyclerview.setAdapter(adapter);
    }
    @Subscribe(code = EventCode.FEEDBACK_IMG)
    public void onImgClick(Integer position){
        if (imgs.get(position).equals(ImageAdapter.DEFAULT_IMG)){
            imgPosition = -1;
            FeedBackActivityPermissionsDispatcher.toChooseImgWithCheck(this,MAX_IMG - imgs.size() + 1);
        }else {
            imgPosition = position;
            FeedBackActivityPermissionsDispatcher.toChooseImgWithCheck(this,1);
        }
    }

    @OnClick({R.id.back, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.btn_commit:
                String message = etContent.getText().toString();
                if (TextUtils.isEmpty(message)){
                    T.show("请先填写反馈信息");
                    return;
                }
                if (message.length() < 10){
                    T.show("反馈内容不能少于10个字符");
                    return;
                }
                showLoadingDialog(true);
                files = new ArrayList<>();
                compressIndex = 0;
                compressImgs();
                break;
        }
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    public void toChooseImg(int max) {
        PhotoPicker.builder()
                .setPhotoCount(max)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(false)
                .start(this, PhotoPicker.REQUEST_CODE);
    }
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(context)
                .setMessage("是否开启相机权限")
                .setPositiveButton("同意", (dialog, button) -> request.proceed())
                .setNegativeButton("拒绝", (dialog, button) -> request.cancel())
                .show();
        Toast.makeText(context, "showRationaleForCamera", Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        Toast.makeText(context, "拒绝相机权限将无法选择图片", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        Toast.makeText(context, "相关权限无法使用", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FeedBackActivityPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logger.d("拍照返回咯"+requestCode+"------------"+resultCode);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) { //RESULT_OK = -1
            if (data != null) {
                List<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (photos == null || photos.size() <= 0){
                    return;
                }
                if (imgPosition == -1){
                    imgs.addAll(0,photos);
                    if (imgs.size() >= 3){
                        imgs.remove(2);
                    }
                }else {
                    imgs.set(imgPosition,photos.get(0));
                }
                adapter.notifyDataSetChanged();
                int c = imgs.size();
                if (imgs.get(c-1).equals(ImageAdapter.DEFAULT_IMG)){
                    c --;
                }
                tvImgCount.setText(c+"/"+MAX_IMG);
            }
        }
    }

    private void compressImgs(){
        if (compressIndex >= MAX_IMG || imgs.get(compressIndex).equals(ImageAdapter.DEFAULT_IMG)){
            presenter.feedBack(etContent.getText().toString(),files);
            return;
        }
        File file = new File(imgs.get(compressIndex));
        Luban.with(this)
                .load(file)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        files.add(file);
                        compressIndex ++;
                        compressImgs();
//
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoadingDialog();
                        e.printStackTrace();
                        T.show("图片压缩失败");
                    }
                }).launch();
    }

    @Override
    public void feedBackS() {
        T.show("提交成功");
        finish();
    }

    @Override
    public void feedBackF(String msg) {
        T.show(msg);
    }
}
